package com.strongbj.iot.devices.amazondb.response.handle;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ContextUtils;
import com.strongbj.iot.devices.amazondb.entity.Tag;
import com.strongbj.iot.devices.amazondb.service.MongoDBService;
import com.strongbj.iot.devices.amazonreader.message.ReaderMessage;
import com.strongbj.iot.devices.amazonreader.request.message.MQBodyMessage;
import com.strongbj.iot.devices.amazonreader.request.message.MQMessage;
import com.strongbj.iot.devices.amazonreader.response.entity.BaseLabelEntity;
import com.strongbj.iot.devices.amazonreader.response.entity.IEntityFactory;
import com.strongbj.iot.devices.amazonreader.response.entity.LabelEntityFactory;
import com.strongbj.iot.devices.amazonreader.response.entity.LedLabelEntity;
import com.strongbj.iot.devices.amazonreader.response.entity.LedLabelKeyState;
import com.strongbj.iot.devices.amazonreader.response.entity.LedLabelLightState;
import com.strongbj.iot.devices.amazonreader.response.entity.LedLabelVoltageState;
import com.strongbj.iot.devices.amazonreader.response.entity.RealtimeLabelInfoListOfReaderEntity;
import com.strongbj.iot.devices.amazonreader.response.entity.RealtimeLabelInfoOfReaderEntity;
import com.strongbj.iot.mq.producer.TopicSender;

import io.netty.channel.ChannelHandlerContext;

/**
 * 主动上传的标签信息的应答处理
 * 
 * @author yuzhantao
 *
 */
class ActivelyUploadedLabelInfoResponseHandle implements IMessageHandle<ReaderMessage, Object> {

	private MongoDBService mongoDBService = (MongoDBService) ContextUtils.getBean("mongoDBService");

	private final static String ACTION_CODE = "daio";
	private final static String MQ_TOPIC = "tasks";
	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");
	private static Logger logger = LogManager.getLogger(ActivelyUploadedLabelInfoResponseHandle.class.getName());

	IEntityFactory<List<BaseLabelEntity>> labelFactory;

	public ActivelyUploadedLabelInfoResponseHandle() {
		this.labelFactory = new LabelEntityFactory();
	}

	@Override
	public boolean isHandle(ReaderMessage t) {
		if (t.getType() == 2) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, ReaderMessage t) {
		byte[] datas = t.getBody(); // 获取从Reader接收到的数据段信息
//		logger.debug("收到Reader主动上传的标签信息数据："+ByteUtil.byteArrToHexString(datas));
		List<BaseLabelEntity> labs = labelFactory.parse(datas); // 通过简单工厂模式将byte数组转为对象
//		logger.info("labs:" + JSON.toJSONString(labs));
		StringBuffer sb = new StringBuffer();
		for (byte b : t.getAddress()) {
			sb.append((b & 0xff) + ".");
		}

//		MQMessage<String> msg = this.baseLabel2MQMessage(
//				sb.toString().substring(0,sb.length()-1), labs);// 将Reader对象信息转为MQ格式的信息
//		
//		String json = JSON.toJSONString(msg);	// 转为Json字符串
//		topicSender.send(MQ_TOPIC, json);		// 发送标签信息到MQ
////		logger.info(json);

		//// 将上传标签插入本地mongoDB进行缓存
		this.baseLabel2Entity(sb.toString().substring(0, sb.length() - 1), labs);

		labs.clear();
		labs = null;
		sb.setLength(0);
		sb = null;
		// msg = null;
		t = null;
		return null;
	}

	/**
	 * 将从Reader获取的标签信息转成实体格式的信息存如mongodb
	 * 
	 * @param readerCode
	 * @param labs
	 * @return
	 */
	private void baseLabel2Entity(String readerCode, List<BaseLabelEntity> labs) {
		try {
			Date d = new Date();
			for (BaseLabelEntity lab : labs) {
				if (lab instanceof LedLabelEntity) {
					LedLabelEntity ledLab = (LedLabelEntity) lab;

					Tag labInfo = new Tag();
					labInfo.setId(ledLab.getId());

					Tag tag = mongoDBService.findById(ledLab.getId());
					if (tag != null) {
						labInfo.setReaderCode(tag.getReaderCode());
					}

					labInfo.setBatterState(ledLab.getVoltage() == LedLabelVoltageState.Normal ? "1" : "2");
					StringBuffer sb = new StringBuffer();
					for (byte b : ledLab.getBaseStationShortAddress()) {
						sb.append(Integer.valueOf(b) + ",");
					}
					labInfo.setShortAddr(sb.toString().substring(0, sb.length() - 1));
					labInfo.setWlightstate(ledLab.getWhiteLed() == LedLabelLightState.On ? "1" : "0");
					labInfo.setGightstate(ledLab.getGreenLed() == LedLabelLightState.On ? "1" : "0");
					labInfo.setBlightstate(ledLab.getBlueLed() == LedLabelLightState.On ? "1" : "0");
					labInfo.setRlightstate(ledLab.getRedLed() == LedLabelLightState.On ? "1" : "0");
					labInfo.setBtnstate(ledLab.getKeyState() == LedLabelKeyState.KeyDown ? "1" : "2");
					labInfo.setUpdateTime(d);
					mongoDBService.save(labInfo);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 将从Reader获取的标签信息转成MQ格式的信息
	 * 
	 * @param readerCode
	 * @param labs
	 * @return
	 */
	private MQMessage<String> baseLabel2MQMessage(String readerCode, List<BaseLabelEntity> labs) {
		MQBodyMessage<RealtimeLabelInfoListOfReaderEntity> msg = new MQBodyMessage<>();

		List<RealtimeLabelInfoOfReaderEntity> list = new ArrayList<>();
		for (BaseLabelEntity lab : labs) {
			if (lab instanceof LedLabelEntity) {
				LedLabelEntity ledLab = (LedLabelEntity) lab;
				RealtimeLabelInfoOfReaderEntity labInfo = new RealtimeLabelInfoOfReaderEntity();
				labInfo.setCard(ledLab.getId());
				labInfo.setBatterState(ledLab.getVoltage() == LedLabelVoltageState.Normal ? "1" : "2");
				StringBuffer sb = new StringBuffer();
				for (byte b : ledLab.getBaseStationShortAddress()) {
					sb.append(Integer.valueOf(b) + ",");
				}
				labInfo.setShortAddr(sb.toString().substring(0, sb.length() - 1));
				labInfo.setWlightstate(ledLab.getWhiteLed() == LedLabelLightState.On ? "1" : "0");
				labInfo.setGightstate(ledLab.getGreenLed() == LedLabelLightState.On ? "1" : "0");
				labInfo.setBlightstate(ledLab.getBlueLed() == LedLabelLightState.On ? "1" : "0");
				labInfo.setRlightstate(ledLab.getRedLed() == LedLabelLightState.On ? "1" : "0");
				labInfo.setBtnstate(ledLab.getKeyState() == LedLabelKeyState.KeyDown ? "1" : "2");
				list.add(labInfo);
			}

		}

		RealtimeLabelInfoListOfReaderEntity labList = new RealtimeLabelInfoListOfReaderEntity();
		labList.setCardlist(list);
		labList.setDevsn(readerCode);

		msg.setPostdata(labList);
		msg.setActioncode(ACTION_CODE);
		msg.setGUID(UUID.randomUUID().toString());

		MQMessage<String> mqMsg = new MQMessage<String>();
		mqMsg.setActionCode(ACTION_CODE);
		mqMsg.setGUDI(UUID.randomUUID().toString());
		mqMsg.setAwsPostdata(JSON.toJSONString(msg));
		return mqMsg;
	}
}
